package com.example.demo.domain.application;

import com.example.demo.domain.application.factory.ApplicationAbstractFactory;
import com.example.demo.domain.category.Category;
import com.example.demo.domain.user.User;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.stereotype.Component;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

/**
 * 个人应用
 *
 * @author yingjianhua
 */
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString(callSuper = true)
@Entity
@DiscriminatorValue("PERSON")
public class PersonApplication extends Application {

    public PersonApplication(String name, String icon) {
        super(name, icon);
    }

    @Override
    public ApplicationScale getScale() {
        return ApplicationScale.PERSON;
    }

    @Override
    protected boolean havePermission(User operator, User user) {
        return operator.equals(user);
    }

    /**
     * 用户对应用进行开通
     *
     * @param operator 操作员
     * @param user 用户
     */
    public void open(User operator, User user) {
        openConstrain();
        permissionConstrain(operator, user);
        mustClose(user);
        openRepository.save(OpenRecord.createPersonScope(this, user));
    }

    /**
     * 用户对应用进行关闭
     *
     * @param operator 操作员
     * @param user 用户
     */
    public void close(User operator, User user) {
        permissionConstrain(operator, user);
        mustOpen(user);
        openRepository.delete(OpenRecord.createPersonScope(this, user));
    }

    @Component
    public static class PersonApplicationFactory implements ApplicationAbstractFactory {

        @Override
        public Application create(String name, Category category, String icon) {
            return new PersonApplication(name, icon);
        }
    }
}
